********************************************************************************
********************************************************************************
* Title:		tables
* Project:		Stress, Ethnicity, and Prosocial Behavior
* Author:		Moritz Poll (moritz.poll@brown.edu)
* PIs:			Johannes Haushofer, Sara Lowes, Abednego Musau, David Ndetei, 
*				Nathan Nunn, Moritz Poll, Nancy Qian
* Purpose:		Builds tables from stored estimates
********************************************************************************
********************************************************************************
noisily dis as input "Start: Tables"

use  "$cleandata_dir/HIO_for_analysis_xlong.dta", clear // for the labels
include "$do_analysis_dir/definitions.do"
global noisyregs ""
set more off
set trace off

********************************************************************************
********************************** Table Notes *********************************
********************************************************************************
* This section defines three types of table notes. General notes are added to
* every table. Specification- and game-specific notes are added only to tables
* which contain that specification or game. Finally, the notes_width makes use
* of the substitute() function in esttab command to ex-post enter the created
* .tex file and edit it. It moves the table from the tabular to the tabularx
* environment which forces table width to a certain length. We use \hsize as it
* automatically adapts to landscape mode. Note that tabularx inserts line breaks
* in row names which may not end up in the desired places and manually editing
* the labels here may be required.
********************************************************************************

local general_notes "Standard errors clustered at the participant level are reported in parentheses. Significance is denoted by \sym{*} \(p<0.1\), \sym{**} \(p<0.05\), \sym{***} \(p<0.01\)."
local notesspec1 "\textit{Notes}: $^a$ The average hydrocortisone effect is calculated as in equation~\eqref{eqn: Calculated Hydro Effect}. $^b$ The average coethnicity effect is calculated as in equation~\eqref{eqn: Calculated Coethnity Effect}. $^c$ The interaction effect is given by $\hat{\beta}_3$ in equation~\eqref{eqn: Main Specification}. All terms are described in the text. In this specification, we control for the interaction of a same-gender and same-age group indicator with hydrocortisone as well as gender, age group and ethnicity fixed effects of both players."
local notesspec2 "\textit{Notes}: The table reports estimates of a version of equation~\eqref{eqn: Main Specification} with player 1 fixed effects. Variables are as described in the text."
local cyd_note "The sample mean and standard deviation for the choose your dictator game refer to the share of decisions in which an in-group member was chosen among the decisions where one was available."
local social_proximity_note "Social proximity refers to the average measures of likelihood to be friends, trust and closeness rescaled to lie between 0 and 1."
local coa07_note "As an alternative in-group definition we employ the 2007 political coalitions of Kikuyu and Kamba versus Luo and Luhya."
local coa17_note "As an alternative in-group definition we employ the 2017 political coalitions of Kikuyu only versus Luo, Luhya, and Kamba."

* Table width depending on number of columns stored in $eststo_counter
local notes_width2  `" "{l}{\footnotesize" "{p{0.75\hsize}}{\footnotesize" "'
local notes_width4  `" "{l}{\footnotesize" "{p{0.73\hsize}}{\footnotesize" "'
local notes_width5  `" "{l}{\footnotesize" "{p{0.93\hsize-10pt}}{\footnotesize" "'
local notes_width6  `" "{l}{\footnotesize" "{p{0.98\hsize}}{\footnotesize" "'
local notes_width8  `" "{l}{\footnotesize" "{p{0.95\hsize}}{\footnotesize" "'
local notes_width10 `" "{l}{\footnotesize" "{p{1.10\hsize}}{\footnotesize" "'
global alignment "S[table-format=1.3]"

local cols = 0
foreach var in $main_table_vars {
	local ++cols
}

local 0 ""

global robustness_checks `""_coa07" "_coa17" "_low_edu" "_high_edu" "_first_same" "_first_diff" "_sessionfe" "_parents_same" "_comprehension" "_viewtime" "_decisiontime" "_continuetime" "_imbalance" "_welsch""' // "_robust" "_female" "_income" "_alwaysNBO" "_guess" "_firstround" "_comprehension_weighted" "_session_length" "_implausible_cortisol" "_dfits" "_cooksd" "_control_social_proximity" "_whitepresent"

********************************************************************************
************************* Specification chart retrieval ************************
********************************************************************************

foreach coeff in diff_eth pill eth_Delta {
	foreach game in cyd dg tg1 tg2 social_proximity {
		mat `game'_`coeff' = . , . , .
		foreach het in $robustness_checks _spec2 {
			mat `game'_`coeff' = `game'_`coeff' \ . , . , .
		}
		mat colnames `game'_`coeff' = `game'_`coeff' `game'_`coeff'_se `game'_`coeff'_p
		mat rownames `game'_`coeff' = _main $robustness_checks  _spec2
	}
}

********************************************************************************
***************************** Publication Tables,  *****************************
***************************** Main Specifications  *****************************
********************************************************************************

forvalues spec = 1 / 2 {
	if `spec' == 1 local robustness_checks `"$robustness_checks"'
	else local robustness_checks ""
	foreach het in "" `robustness_checks' { // If necessary, the above line can be edited to run some robustness checks for the second specification (player 1 fixed effects) as well.
		local x "eth"
		local xlabel "coethnicity"
		local Xlabel "Coethnicity"
		if "`het'" == "_coa07" local x "coa07"
		if "`het'" == "_coa17" local x "coa17"
		if "`het'" == "_coa07" | "`het'" == "_coa17" local xlabel "political coalition"
		if "`het'" == "_coa07" | "`het'" == "_coa17" local Xlabel "Political coalition"
		local mtitles `""\specialcell{Choose Your \\ Dictator Game}" "\specialcell{Dictator \\ Game}" "\specialcell{Trust \\ Game 1}" "\specialcell{Trust \\ Game 2}" "\specialcell{Social \\ Proximity}" "\specialcell{Choose Your \\ Dictator Game}" "\specialcell{Dictator \\ Game}" "\specialcell{Trust \\ Game 1}" "\specialcell{Trust \\ Game 2}" "\specialcell{Social \\ Proximity}""'
		local pattern "1 0 0 0 0 1 0 0 0 0"
		local extracols "extracols(`=`cols'+1')" // Add an additional empty column after the main columns of a left-right split table
		local cyd_notes `cyd_note'
		* The following tables don't require all columns
		if `spec' == 2 | "`het'" == "_first_same" | "`het'" == "_first_diff" | "`het'" == "_imbalance" {
			local mtitles `""\specialcell{Dictator \\ Game}" "\specialcell{Trust \\ Game 1}" "\specialcell{Trust \\ Game 2}" "\specialcell{Social \\ Proximity}" "\specialcell{Dictator \\ Game}" "\specialcell{Trust \\ Game 1}" "\specialcell{Trust \\ Game 2}" "\specialcell{Social \\ Proximity}""' // No CYD
			local pattern "1 0 0 0 1 0 0 0"
			local extracols "extracols(`=`cols'')"
			local cyd_notes ""
		}
		eststo clear
		foreach game in $main_table_vars {
			if "`game'" == "cyd" & (`spec' == 2 | "`het'" == "_first_same" | "`het'" == "_imbalance") continue // Individual fixed effects not identified in CYD; No such restriction for CYD; individual characteristics are not identified in CYD.
			
			local rest `het'
			include "$do_analysis_dir/sample_restrictions.do"
			if "`het'" == "_imbalance" local if_restriction ""
			
			if "`if_restriction'" == "" local if `"if game_str == "`game'""'
			else local if  `"`if_restriction' & game_str == "`game'""'
			if "`if_restriction'" == "" local if_cyd `"if game == 2 & cyd_owneth_available"'
			else local if_cyd  `"`if_restriction' & game == 2 & cyd_owneth_available"'
			
			eststo `game': estimates use "$estimates_dir/`game'_spec`spec'`het'"
			if "`game'" != "cyd" { // Dictator Game, Trust Game and Social Proximity
				estadd local clust = "{" + string(e(N_clust)		,"%6.0fc") + "}" // The {} serve to avoid the scientific alignment
				estadd local obs   = "{" + string(e(N)				,"%6.0fc") + "}"
				estadd local dec   = "{" + string(e(N)/e(N_clust)	,"%6.0fc") + "}"
				if "`game'" != "social_proximity" $noisyregs sum share `if'
				else $noisyregs sum decision `if'
				estadd local mean = string(r(mean),"%9.`=$precision'f")
				estadd local sd = "(" + string(r(sd),"%9.`=$precision'f") + ")"
				
				* Sample-specific weighting
				$noisyregs sum treatment `if'
				local share_hydro = r(mean)
				$noisyregs sum _same_`x' `if'
				local share_same_`x' = r(mean)
				$noisyregs sum _same_sex `if'
				local share_same_sex = r(mean)
				$noisyregs sum _same_age `if'
				local share_same_age = r(mean)
				
				if `spec' == 1 {
					** Pooled estimators (at the mean)
					lincom _b[1._same_`x'] + `share_hydro'*_b[1._same_`x'#1.treatment]
					if "`het'" == "" local het "_main"
					mat `game'_diff_eth[rownumb(`game'_diff_eth,"`het'"),1] = r(estimate)
					mat `game'_diff_eth[rownumb(`game'_diff_eth,"`het'"),2] = r(se)
					mat `game'_diff_eth[rownumb(`game'_diff_eth,"`het'"),3] = 2*ttail(r(df),abs(r(estimate)/r(se)))
					if "`het'" == "_main" local het ""
					pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(r(df),abs(r(estimate)/r(se)))') precision($precision)
					estadd local diff_eth	  = r(bstar)
					estadd local diff_eth_SE  = r(sestar)
					lincom _b[1.treatment] + `share_same_`x''*_b[1._same_`x'#1.treatment] + ///
											 `share_same_sex'*_b[1._same_sex#1.treatment] + ///
											 `share_same_age'*_b[1._same_age#1.treatment]
					if "`het'" == "" local het "_main"
					mat `game'_pill[rownumb(`game'_pill,"`het'"),1] = r(estimate)
					mat `game'_pill[rownumb(`game'_pill,"`het'"),2] = r(se)
					mat `game'_pill[rownumb(`game'_pill,"`het'"),3] = 2*ttail(r(df),abs(r(estimate)/r(se)))
					if "`het'" == "_main" local het ""
					pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(r(df),abs(r(estimate)/r(se)))') precision($precision)
					estadd local pill	  = r(bstar)
					estadd local pill_SE  = r(sestar)
					
					** Interaction
					lincom _b[1._same_`x'#1.treatment]
					if "`het'" == "" local het "_main"
					mat `game'_eth_Delta[rownumb(`game'_eth_Delta,"`het'"),1] = r(estimate)
					mat `game'_eth_Delta[rownumb(`game'_eth_Delta,"`het'"),2] = r(se)
					mat `game'_eth_Delta[rownumb(`game'_eth_Delta,"`het'"),3] = 2*ttail(r(df),abs(r(estimate)/r(se)))
					if "`het'" == "_main" local het ""
					pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(r(df),abs(r(estimate)/r(se)))') precision($precision)
					estadd local eth_Delta   = r(bstar)
					estadd local eth_DeltaSE = r(sestar)
				}
				if `spec' == 2 {
					** Pooled estimators (at the mean)
					lincom _b[1._same_`x'] + `share_hydro'*_b[1._same_`x'#1.treatment]
					if "`het'" == "" local het "_spec2"
					mat `game'_diff_eth[rownumb(`game'_diff_eth,"`het'"),1] = r(estimate)
					mat `game'_diff_eth[rownumb(`game'_diff_eth,"`het'"),2] = r(se)
					mat `game'_diff_eth[rownumb(`game'_diff_eth,"`het'"),3] = 2*ttail(r(df),abs(r(estimate)/r(se)))
					if "`het'" == "_spec2" local het ""
					pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(r(df),abs(r(estimate)/r(se)))') precision($precision)
					estadd local diff_eth	  = r(bstar)
					estadd local diff_eth_SE  = r(sestar)
					
					**Interaction
					lincom _b[1._same_`x'#1.treatment]
					if "`het'" == "" local het "_spec2"
					mat `game'_eth_Delta[rownumb(`game'_eth_Delta,"`het'"),1] = r(estimate)
					mat `game'_eth_Delta[rownumb(`game'_eth_Delta,"`het'"),2] = r(se)
					mat `game'_eth_Delta[rownumb(`game'_eth_Delta,"`het'"),3] = 2*ttail(r(df),abs(r(estimate)/r(se)))
					if "`het'" == "_spec2" local het ""
					pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(r(df),abs(r(estimate)/r(se)))') precision($precision)
					estadd local eth_Delta   = r(bstar)
					estadd local eth_DeltaSE = r(sestar)
				}
			}
			else { // CYD
				estadd local clust = "{" + string(e(N_clust)		,"%6.0fc") + "}" // The {} serve to avoid the scientific alignment
				estadd local obs   = "{" + string(e(N)				,"%6.0fc") + "}" // Adjust number of choices to number of decisions in CYD
				estadd local dec   = "{" + string(e(N)/e(N_clust)	,"%6.0fc") + "}"
				sum cyd_same_eth_chosen `if_cyd'
				estadd local mean = string(r(mean),"%9.`=$precision'f")
				estadd local sd = "(" + string(r(sd),"%9.`=$precision'f") + ")"
				
				* Sample-specific weighting
				$noisyregs sum treatment `if_cyd'
				local share_hydro = r(mean)
				$noisyregs sum _same_`x' `if_cyd'
				local share_same_`x' = r(mean)
				$noisyregs sum _same_sex `if_cyd'
				local share_same_sex = r(mean)
				$noisyregs sum _same_age `if_cyd'
				local share_same_age = r(mean)
					
				** Pooled estimators
				lincom _b[_same_`x'] + `share_hydro'*_b[_same_`x'#1.treatment]
				if "`het'" == "" local het "_main"
				mat `game'_diff_eth[rownumb(`game'_diff_eth,"`het'"),1] = r(estimate)
				mat `game'_diff_eth[rownumb(`game'_diff_eth,"`het'"),2] = r(se)
				mat `game'_diff_eth[rownumb(`game'_diff_eth,"`het'"),3] = 2*ttail(r(df),abs(r(estimate)/r(se)))
				if "`het'" == "_main" local het ""
				pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(e(N)-e(df_m),abs(r(estimate)/r(se)))') precision($precision)
				estadd local diff_eth	  = r(bstar)
				estadd local diff_eth_SE  = r(sestar)
				
				** Interaction
				lincom _b[_same_`x'#1.treatment]
				if "`het'" == "" local het "_main"
				mat `game'_eth_Delta[rownumb(`game'_eth_Delta,"`het'"),1] = r(estimate)
				mat `game'_eth_Delta[rownumb(`game'_eth_Delta,"`het'"),2] = r(se)
				mat `game'_eth_Delta[rownumb(`game'_eth_Delta,"`het'"),3] = 2*ttail(r(df),abs(r(estimate)/r(se)))
				if "`het'" == "_main" local het ""
				pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(e(N)-e(df_m),abs(r(estimate)/r(se)))') precision($precision)
				estadd local eth_Delta   = r(bstar)
				estadd local eth_DeltaSE = r(sestar)
			}
		} // Games
		
		if `spec' == 2 & "`het'" == "" local 0 "\multicolumn{`=`cols'-1'}{c}{Player 1 Fixed Effects}"
		
		local alignment = $eststo_counter * "$alignment"
			
		** Short form table: Three-panel design, ethnicity-only and pill-only specifications up top, shorter interaction panel below **
		if `spec' == 1 local short_stats	`"stats(mean sd pill pill_SE  diff_eth diff_eth_SE  eth_Delta eth_DeltaSE  clust dec obs, labels("Sample mean" "Sample standard deviation" "\midrule\multicolumn{4}{l}{\textit{Panel A: Average hydrocortisone effect$^a$}} \\ \quad Hydrocortisone effect" " " 	"\midrule \multicolumn{4}{l}{\textit{Panel B: Average `xlabel' effect$^b$}} \\ \quad `Xlabel' effect" " " "\midrule\multicolumn{4}{l}{\textit{Panel C: Interaction of hydrocortisone and `xlabel'$^c$}} \\ \quad Interaction effect" " " "\midrule Participants" "Decisions per participant" "Decisions")) "'
		if `spec' == 2 local short_stats	`"stats(mean sd               diff_eth diff_eth_SE  eth_Delta eth_DeltaSE  clust dec obs, labels("Sample mean" "Sample standard deviation" "\midrule \multicolumn{4}{l}{\textit{Panel A: Average `xlabel' effect$^a$}} \\ \quad `Xlabel' effect" " " "\midrule\multicolumn{4}{l}{\textit{Panel B: Interaction of hydrocortisone and `xlabel'$^b$}} \\ \quad Interaction effect" " " "\midrule Participants" "Decisions per participant" "Decisions")) "'
			
		esttab using "$tables_dir/spec`spec'`het'.tex", $table_design drop(*) ///
			`short_cons_label' `short_stats' mtitles(`mtitles') alignment(`alignment') ///
			nonotes addnotes(`notesspec`spec'' `cyd_notes' `social_proximity_note' `="`coa07_note'"*("`het'"=="_coa07")' `="`coa17_note'"*("`het'"=="_coa17")' `general_notes') /// `cyd_note'
			substitute(\_ _ l*{8} l*{9} l*{10} l*{11} `notes_width`=$eststo_counter'')
		noisily dis as result "Successfully created Table specification `spec'`het'."
	}
}
********************************************************************************
*************** Full coefficient readout for main results tables ***************
********************************************************************************

forvalues spec = 1 / 2 {
	eststo clear
	local mtitles `""\specialcell{Choose Your \\ Dictator Game}" "\specialcell{Dictator \\ Game}" "\specialcell{Trust \\ Game 1}" "\specialcell{Trust \\ Game 2}" "\specialcell{Social \\ Proximity}" "\specialcell{Choose Your \\ Dictator Game}" "\specialcell{Dictator \\ Game}" "\specialcell{Trust \\ Game 1}" "\specialcell{Trust \\ Game 2}" "\specialcell{Social \\ Proximity}""'
	if `spec' == 2 local mtitles `""\specialcell{Dictator \\ Game}" "\specialcell{Trust \\ Game 1}" "\specialcell{Trust \\ Game 2}" "\specialcell{Social \\ Proximity}" "\specialcell{Dictator \\ Game}" "\specialcell{Trust \\ Game 1}" "\specialcell{Trust \\ Game 2}" "\specialcell{Social \\ Proximity}""' // No CYD
	foreach game in $main_table_vars {
		if `spec' == 2 & "`game'" == "cyd" continue // Not identified
		eststo: estimates use "$estimates_dir/`game'_spec`spec'"
		if "`game'" != "cyd" {
			estadd local clust = "{" + string(e(N_clust)		,"%6.0fc") + "}"
			estadd local obs   = "{" + string(e(N)				,"%6.0fc") + "}"
			estadd local dec   = "{" + string(e(N)/e(N_clust)	,"%6.0fc") + "}"
		}
		else {
			estadd local clust = "{" + string(e(N_clust)		,"%6.0fc") + "}"
			estadd local obs   = "{" + string(e(N)				,"%6.0fc") + "}"
			estadd local dec   = "{" + string(e(N)/e(N_clust)	,"%6.0fc") + "}"
		}
	}
	local order order(_cons 1.treatment)
	if `spec' == 2 local order order(_cons)
	local notewidth = 0.98
	if `spec' == 2 local notewidth = 0.8
	esttab using "$tables_dir/spec`spec'_long.tex", b($precision) se label booktabs star(* 0.1 ** 0.05 *** 0.01) `order' replace ///
		stats(clust dec obs, labels("Participants" "Decisions per participant" "Decisions")) ///
		noomitted nobaselevels mtitles(`mtitles') alignment(`alignment') ///
		nonotes addnotes(\textit{Notes}: This table presents the full regression output of our main specification. All terms are described in the text. In this specification, we control for the interaction of a same-gender and same-age group indicator with hydrocortisone as well as gender, age group and ethnicity fixed effects of both players. `social_proximity_note' `general_notes') ///
		rename(_same_eth 1._same_eth _same_sex 1._same_sex _same_age 1._same_age 1.treatment#c._same_eth 1.treatment#1._same_eth 1.treatment#c._same_sex 1.treatment#1._same_sex 1.treatment#c._same_age 1.treatment#1._same_age) ///
		substitute(\_ _ "{l}{\footnotesize" "{p{`notewidth'\hsize}}{\footnotesize" "Proximity}}\\" "Proximity}}\\\midrule")
}

********************************************************************************
**************************** CYD LPM vs logit **********************************
********************************************************************************
{
eststo clear
local spec = 1
eststo: estimates use "$estimates_dir/cyd_spec`spec'"
estadd local clust = "{" + string(e(N_clust)		,"%6.0fc") + "}"
estadd local obs   = "{" + string(e(N)				,"%6.0fc") + "}"
estadd local dec   = "{" + string(e(N)/e(N_clust)	,"%6.0fc") + "}"

local v _same_eth  _same_coa07  _same_coa17  _same_sex  _same_age  $cyd_controls
foreach var in `v' {
	capture rename `var' `var'0
	rename cyd_diff`var' `var'
}
foreach var in _same_eth  _same_coa07  _same_coa17  _same_sex  _same_age {
	rename hydro`var' hydro`var'0
	gen hydro`var' = treatment * `var'
}
keep if game_str == "cyd"
logit   decision _same_eth  hydro_same_eth  _same_sex  hydro_same_sex  _same_age  hydro_same_age  $cyd_controls `if_restriction', cluster(ID)
eststo: margins, dydx(*) post // This regression has to be run here as the margins command cannot use restored estimation results.
	estadd local clust = "{" + string(e(N)/6		,"%6.0fc") + "}"
	estadd local obs   = "{" + string(e(N)			,"%6.0fc") + "}"
	estadd local dec   = "{" + string(6	,"%6.0fc") + "}"

use  "$cleandata_dir/HIO_for_analysis_xlong.dta", clear // for the labels
label var _same_eth "Same ethnicity"
label var _same_sex "Same gender"
label var _same_age "Same age group"

esttab using "$tables_dir/spec`spec'_cyd_logit.tex", b($precision) se label booktabs star(* 0.1 ** 0.05 *** 0.01) replace ///
	rename(1._same_eth _same_eth hydro_same_eth 1.treatment#c._same_eth 1._same_sex _same_sex hydro_same_sex 1.treatment#c._same_sex 1._same_age _same_age hydro_same_age 1.treatment#c._same_age cyd_left_person _cons) /// 
	noomitted nobaselevels order(_cons) ///
	stats(clust dec obs, labels("Participants" "Decisions per participant" "Decisions")) mtitles("\specialcell{Choose Your \\ Dictator Game \\ Linear Probability}" "\specialcell{Choose Your \\ Dictator Game \\ Conditional Logit}") alignment(`alignment') ///
	mgroup("\multicolumn{2}{c}{Choose your dictator game LPM and logit}", span) nonotes addnotes(\textit{Notes}: The table presents the results of the choose your dictator game in both a linear probability and conditional logit specification. `general_notes') ///
	substitute(\_ _ l*{8} l*{9} l*{10} l*{11} "{l}{\footnotesize" "{p{.85\hsize-10pt}}{\vspace{-.25cm}\footnotesize" "Logit}}\\" "Logit}}\\\midrule")
}
********************************************************************************
*************************** Randomization inference ****************************
********************************************************************************

global reps 10000
local spec = 1
local x "eth"
local xlabel "coethnicity"
local Xlabel "Coethnicity"
local mtitles `""\specialcell{Choose Your \\ Dictator Game}" "\specialcell{Dictator \\ Game}" "\specialcell{Trust \\ Game 1}" "\specialcell{Trust \\ Game 2}" "\specialcell{Social \\ Proximity}" "\specialcell{Choose Your \\ Dictator Game}" "\specialcell{Dictator \\ Game}" "\specialcell{Trust \\ Game 1}" "\specialcell{Trust \\ Game 2}" "\specialcell{Social \\ Proximity}""'
local pattern "1 0 0 0 0 1 0 0 0 0"
local extracols ""
eststo clear

* Load relevant data
foreach matrix in diff_eth pill eth_Delta {
	use "$estimates_dir/ri_`matrix'_spec`spec'_reps${reps}.dta", clear
	mkmat Sampling_p Randomization_Inference_p, matrix(`matrix')
	mat rownames `matrix' = $main_table_vars
}

foreach game in $main_table_vars {
	if `spec' == 2 & "`game'" == "cyd" continue // Not identified
	eststo: estimates use "$estimates_dir/`game'_spec`spec'"
	* Load means
	preserve
	use  "$cleandata_dir/HIO_for_analysis_xlong.dta", clear
	if "`game'" == "cyd" sum cyd_same_eth_chosen if game == 2 & cyd_owneth_available
	else if "`game'" != "social_proximity" sum share if game_str == "`game'"
	else sum decision if game_str == "`game'"
	estadd local mean = string(r(mean),"%9.`=$precision'f")
	estadd local sd = "(" + string(r(sd),"%9.`=$precision'f") + ")"
			
	* Sample-specific weighting
	$noisyregs sum treatment `if'
	local share_hydro = r(mean)
	$noisyregs sum _same_`x' `if'
	local share_same_`x' = r(mean)
	$noisyregs sum _same_sex `if'
	local share_same_sex = r(mean)
	$noisyregs sum _same_age `if'
	local share_same_age = r(mean)
	restore
	
	if "`game'" != "cyd" { // Dictator Game, Trust Game and Social Proximity
		estadd local clust = "{" + string(e(N_clust)		,"%6.0fc") + "}" // The {} serve to avoid the scientific alignment
		estadd local obs   = "{" + string(e(N)				,"%6.0fc") + "}"
		estadd local dec   = "{" + string(e(N)/e(N_clust)	,"%6.0fc") + "}"
		
			foreach matrix in pill diff_eth eth_Delta {
					
				** Pooled estimators (at the mean)
				if "`matrix'" == "diff_eth"  $noisyregs lincom _b[1._same_`x'] + `share_hydro'*_b[1._same_`x'#1.treatment]
				
				if "`matrix'" == "pill" $noisyregs lincom _b[1.treatment] + `share_same_`x''*_b[1._same_`x'#1.treatment] + ///
																			`share_same_sex'*_b[1._same_sex#1.treatment] + ///
																			`share_same_age'*_b[1._same_age#1.treatment]
																			
				if "`matrix'" == "eth_Delta"  $noisyregs lincom _b[1._same_`x'#1.treatment]
				$noisyregs pstar, b(`r(estimate)') p(`=`matrix'[rownumb(`matrix',"`game'"),colnumb(`matrix',"Randomization_Inference_p")]') precision($precision) pbrackets
				estadd local `matrix'   = r(bstar)
				estadd local `matrix'_p = r(pstar)
			}
	}
	else { // CYD
		estadd local clust = "{" + string(e(N_clust)		,"%6.0fc") + "}" // The {} serve to avoid the scientific alignment
		estadd local obs   = "{" + string(e(N)				,"%6.0fc") + "}" // Adjust number of choices to number of decisions in CYD
		estadd local dec   = "{" + string(e(N)/e(N_clust)	,"%6.0fc") + "}"
		
		foreach matrix in diff_eth eth_Delta {
			if "`matrix'" == "diff_eth"   lincom _b[_same_`x'] + `share_same_`x''*_b[_same_`x'#1.treatment]
			if "`matrix'" == "eth_Delta"  lincom _b[_same_`x'#1.treatment]
			$noisyregs pstar, b(`r(estimate)') p(`=`matrix'[rownumb(`matrix',"`game'"),colnumb(`matrix',"Randomization_Inference_p")]') precision($precision) pbrackets
			estadd local `matrix'   = r(bstar)
			estadd local `matrix'_p = r(pstar)
		}
	}
} // Games

local stats `"stats(mean sd  pill pill_p  diff_eth diff_eth_p  eth_Delta eth_Delta_p  clust dec obs, labels("Sample mean" "Sample standard deviation" "\midrule\multicolumn{4}{l}{\textit{Panel A: Average hydrocortisone effect$^a$}} \\ \quad Hydrocortisone effect" " " "\midrule \multicolumn{4}{l}{\textit{Panel B: Average `xlabel' effect$^b$}} \\ \quad `Xlabel' effect" " " "\midrule\multicolumn{4}{l}{\textit{Panel C: Interaction of `xlabel' and hydrocortisone$^c$}} \\ \quad Interaction effect" " " "\midrule Participants" "Decisions per participant" "Decisions")) "'

local reps = string($reps, "%6.0fc")

local alignment = $eststo_counter * "$alignment"

** Long form table **
esttab using "$tables_dir/spec`spec'_ri${reps}.tex", $table_design ///
	drop(*) mgroups("\multicolumn{5}{c}{Randomization inference \$p\$-values}", pattern(`pattern') span) `extracols' /// The extracols option does not adapt the number of columns.
	`cons_label' `stats' mtitles(`mtitles') ///
	alignment(`alignment') ///
	nonotes addnotes(`notesspec`spec'' `cyd_note' `social_proximity_note' The \$p\$-values in brackets are obtained from `reps' randomization inference draws and significance denoted by \sym{*} \(p<0.1\), \sym{**} \(p<0.05\), \sym{***} \(p<0.01\).) ///
	substitute(\_ _ l*{8} l*{9} l*{10} l*{11} `notes_width`=$eststo_counter'')
noisily dis as result "Successfully created Table specification `spec' Randomization inference with $reps repetitions."

********************************************************************************
************************** Experimenter Demand Module **************************
********************************************************************************

use  "$cleandata_dir/HIO_for_analysis_xlong.dta", clear
label var demandeffects "Demand Treatment" // "Explicit experimenter demand prime"
label var demand_primetime "Seconds viewing prime"
eststo clear
foreach spec in "" "treatment0" "treatment1" "_same_eth0" "_same_eth1" {
	eststo: estimates use "$estimates_dir/demand`spec'"
	lincom _b[demandeffects]
	pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(r(df),abs(r(estimate)/r(se)))') precision($precision)
	estadd local demand	   = r(bstar)
	estadd local demand_SE = r(sestar)
	estadd local clust = "{" + string(e(N_clust)		,"%6.0fc") + "}" // The {} serve to avoid the scientific alignment
	estadd local obs   = "{" + string(e(N)				,"%6.0fc") + "}" // Adjust number of choices to number of decisions in CYD
	estadd local dec   = "{" + string(e(N)/e(N_clust)	,"%6.0fc") + "}"
	
	if "`spec'" == "" sum share
	else {
		local if = substr("`spec'",1,`=strlen("`spec'")-1') + "==" + substr("`spec'",-1,.)
		sum share if `if'
	}
	estadd local mean = string(r(mean),"%9.`=$precision'f")
	estadd local sd = "(" + string(r(sd),"%9.`=$precision'f") + ")"
}
local short_stats `"stats(mean  sd  demand  demand_SE  obs, labels("Sample mean" "Sample standard deviation"  "\midrule Demand Treatment" " " "\midrule Participants/Decisions")) "'
esttab using "$tables_dir/demand.tex", b($precision) se label booktabs star(* 0.1 ** 0.05 *** 0.01) replace /// $table_design /// 
	noomitted nobaselevels drop(*) ///
	`short_stats' mtitles("\specialcell{Full\\sample}" "\specialcell{Hydrocortisone\\pill}" "\specialcell{Placebo\\pill}" "\specialcell{Coethnic\\pairing}" "\specialcell{Non-coethnic\\pairing}") alignment(`alignment') ///
	mgroup("\multicolumn{5}{c}{Share Allocated in Experimenter Demand Module}", span) nonotes addnotes(\textit{Notes}: The table presents the results of the experimenter demand module. Participants played an additional round of the dictator game and were randomly allocated to either an explicit experimenter demand or not. Standard errors are reported in parentheses. Significance is denoted by \sym{*} \(p<0.1\), \sym{**} \(p<0.05\), \sym{***} \(p<0.01\).) ///
	substitute(\_ _ l*{8} l*{9} l*{10} l*{11} "{l}{\footnotesize" "{p{.95\hsize-10pt}}{\vspace{-.25cm}\footnotesize")
noisily dis as result "Successfully created Experimenter Demand Table."

********************************************************************************
*************************** TG2 Tables by allocation ***************************
********************************************************************************

use  "$cleandata_dir/HIO_for_analysis_xlong.dta", clear
local spec = 1
eststo clear
local x eth
local xlabel "coethnicity"
local Xlabel "Coethnicity"
local game tg2
foreach allocation in "game_fe" 120 240 360 480 600 {
	eststo: estimates use "$estimates_dir/tg2_spec`spec'_`allocation'"
	estadd local clust = "{" + string(e(N_clust)		,"%6.0fc") + "}"
	estadd local obs   = "{" + string(e(N)				,"%6.0fc") + "}"
	estadd local dec   = "{" + string(e(N)/e(N_clust)	,"%6.0fc") + "}"
	
	if "`allocation'" == "game_fe" sum share if game_str == "`game'"
	else {
		sum share if game_str == "`game'" & game == `=`allocation'/120+4'
	}
	estadd local mean = string(r(mean),"%9.`=$precision'f")
	estadd local sd = "(" + string(r(sd),"%9.`=$precision'f") + ")"
				
	* Sample-specific weighting
	if "`allocation'" == "game_fe" {
		* Sample-specific weighting
		$noisyregs sum treatment if game_str == "`game'"
		local share_hydro = r(mean)
		$noisyregs sum _same_`x' if game_str == "`game'"
		local share_same_`x' = r(mean)
		$noisyregs sum _same_sex if game_str == "`game'"
		local share_same_sex = r(mean)
		$noisyregs sum _same_age if game_str == "`game'"
		local share_same_age = r(mean)		
	}
	else {
		$noisyregs sum treatment  if game_str == "`game'" & game == `=`allocation'/120+4'
		local share_hydro = r(mean)
		$noisyregs sum _same_`x'  if game_str == "`game'" & game == `=`allocation'/120+4'
		local share_same_`x' = r(mean)
		$noisyregs sum _same_sex  if game_str == "`game'" & game == `=`allocation'/120+4'
		local share_same_sex = r(mean)
		$noisyregs sum _same_age  if game_str == "`game'" & game == `=`allocation'/120+4'
		local share_same_age = r(mean)
	}

	if `spec' == 1 {
		** Pooled estimators (at the mean)
		lincom _b[1._same_`x'] + `share_hydro'*_b[1._same_`x'#1.treatment]
		pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(r(df),abs(r(estimate)/r(se)))') precision($precision)
		estadd local diff_eth	  = r(bstar)
		estadd local diff_eth_SE  = r(sestar)
		
		lincom _b[1.treatment] + `share_same_`x''*_b[1._same_`x'#1.treatment] + ///
								 `share_same_sex'*_b[1._same_sex#1.treatment] + ///
								 `share_same_age'*_b[1._same_age#1.treatment]
		pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(r(df),abs(r(estimate)/r(se)))') precision($precision)
		estadd local pill	  = r(bstar)
		estadd local pill_SE  = r(sestar)
		
		lincom _b[1._same_`x'#1.treatment]
		pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(r(df),abs(r(estimate)/r(se)))') precision($precision)
		estadd local eth_Delta   = r(bstar)
		estadd local eth_DeltaSE = r(sestar)
		
		local stats	`"stats(mean sd pill pill_SE  diff_eth diff_eth_SE  eth_Delta eth_DeltaSE  clust dec obs, labels("Sample mean" "Sample standard deviation" "\midrule\multicolumn{4}{l}{\textit{Panel A: Average hydrocortisone effect$^a$}} \\ \quad Hydrocortisone effect" " " "\midrule \multicolumn{4}{l}{\textit{Panel B: Average `xlabel' effect$^b$}} \\ \quad `Xlabel' effect" " " "\midrule\multicolumn{4}{l}{\textit{Panel C: Interaction of hydrocortisone and `xlabel'$^c$}} \\ \quad Interaction effect" " " "\midrule Participants" "Decisions per participant" "Decisions")) "'
	}
	if `spec' == 2 {
		** Pooled estimators (at the mean)
		lincom _b[1._same_`x'] + `share_hydro'*_b[1._same_`x'#1.treatment]
		pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(r(df),abs(r(estimate)/r(se)))') precision($precision)
		estadd local diff_eth	  = r(bstar)
		estadd local diff_eth_SE  = r(sestar)
		
		lincom _b[1._same_`x'#1.treatment]
		pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(r(df),abs(r(estimate)/r(se)))') precision($precision)
		estadd local eth_Delta   = r(bstar)
		estadd local eth_DeltaSE = r(sestar)
		
		local stats	`"stats(mean sd               diff_eth diff_eth_SE  eth_Delta eth_DeltaSE  clust dec obs, labels("Sample mean" "Sample standard deviation" "\midrule \multicolumn{4}{l}{\textit{Panel A: Average `xlabel' effect$^a$}} \\ \quad `Xlabel' effect" " " "\midrule\multicolumn{4}{l}{\textit{Panel B: Interaction of hydrocortisone and `xlabel'$^b$}} \\ \quad Interaction effect" " " "\midrule Participants" "Decisions per participant" "Decisions"))"'
	}
}
if `spec' == 1 local drop "drop(*)"
else local drop ""

local alignment = $eststo_counter * "$alignment"

esttab using "$tables_dir/spec`spec'_tg2.tex", $table_design ///
	`cons_label' `stats' `drop'  /// 
	mtitles("\specialcell{Trust \\ Game 2 \\ Amount FE}" "\specialcell{Trust \\ Game 2 \\ 120 KES}" "\specialcell{Trust \\ Game 2 \\ 240 KES}" "\specialcell{Trust \\ Game 2 \\ 360 KES}" "\specialcell{Trust \\ Game 2 \\ 480 KES}" "\specialcell{Trust \\ Game 2 \\ 600 KES}") ///
	alignment(`alignment') ///
	nonotes addnotes(`notesspec`spec'' `general_notes') ///
	substitute(\_ _ `notes_width`=$eststo_counter'')
noisily dis as result "Successfully created TG2 specification `spec' Table by amounts."

********************************************************************************
******************** Social Proximity by individual measure ********************
********************************************************************************

local spec = 1
eststo clear
local x eth
local xlabel "coethnicity"
local Xlabel "Coethnicity"
foreach game in social_proximity likely_to_be_friends trust closeness {
	eststo: estimates use "$estimates_dir/`game'_spec`spec'"
	estadd local clust = "{" + string(e(N_clust)		,"%6.0fc") + "}"
	estadd local obs   = "{" + string(e(N)				,"%6.0fc") + "}"
	estadd local dec   = "{" + string(e(N)/e(N_clust)	,"%6.0fc") + "}"
	sum decision if game_str == "`game'"
	estadd local mean = string(r(mean),"%9.`=$precision'f")
	estadd local sd = "(" + string(r(sd),"%9.`=$precision'f") + ")"
				
	* Sample-specific weighting
	$noisyregs sum treatment if game_str == "`game'"
	local share_hydro = r(mean)
	$noisyregs sum _same_`x' if game_str == "`game'"
	local share_same_`x' = r(mean)
	$noisyregs sum _same_sex if game_str == "`game'"
	local share_same_sex = r(mean)
	$noisyregs sum _same_age if game_str == "`game'"
	local share_same_age = r(mean)
	
	if `spec' == 1 {
		** Pooled estimators (at the mean)
		lincom _b[1._same_`x'] + `share_hydro'*_b[1._same_`x'#1.treatment]
		pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(r(df),abs(r(estimate)/r(se)))') precision($precision)
		estadd local diff_eth	  = r(bstar)
		estadd local diff_eth_SE  = r(sestar)
		
		lincom _b[1.treatment] + `share_same_`x''*_b[1._same_`x'#1.treatment] + ///
								 `share_same_sex'*_b[1._same_sex#1.treatment] + ///
								 `share_same_age'*_b[1._same_age#1.treatment]
		pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(r(df),abs(r(estimate)/r(se)))') precision($precision)
		estadd local pill	  = r(bstar)
		estadd local pill_SE  = r(sestar)
		
		lincom _b[1._same_`x'#1.treatment]
		pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(r(df),abs(r(estimate)/r(se)))') precision($precision)
		estadd local eth_Delta   = r(bstar)
		estadd local eth_DeltaSE = r(sestar)
		
		local stats	`"stats(mean sd  pill pill_SE  diff_eth  diff_eth_SE  eth_Delta eth_DeltaSE  clust dec obs, labels("Sample mean" "Sample standard deviation" "\midrule\multicolumn{4}{l}{\textit{Panel A: Average hydrocortisone effect$^a$}} \\ \quad Hydrocortisone effect" " " "\midrule \multicolumn{4}{l}{\textit{Panel B: Average `xlabel' effect$^b$}} \\ \quad `Xlabel' effect" " " "\midrule\multicolumn{4}{l}{\textit{Panel C: Interaction of hydrocortisone and `xlabel'$^c$}} \\ \quad Interaction effect" " " "\midrule Participants" "Decisions per participant" "Decisions")) "'
		}
	if `spec' == 2 {
		** Pooled estimators (at the mean)
		lincom _b[1._same_`x'] + `share_hydro'*_b[1._same_`x'#1.treatment]
		pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(r(df),abs(r(estimate)/r(se)))') precision($precision)
		estadd local diff_eth	  = r(bstar)
		estadd local diff_eth_SE  = r(sestar)
		
		lincom _b[1._same_`x'#1.treatment]
		pstar, b(`r(estimate)') se(`r(se)') p(`=2*ttail(r(df),abs(r(estimate)/r(se)))') precision($precision)
		estadd local eth_Delta   = r(bstar)
		estadd local eth_DeltaSE = r(sestar)
		local stats	`"stats(mean sd  diff_eth diff_eth_SE  eth_Delta eth_DeltaSE  clust dec obs, labels("Sample mean" "Sample standard deviation" "\midrule \multicolumn{4}{l}{\textit{Panel A: Average `xlabel' effect$^a$}} \\ \quad `Xlabel' effect" " " "\midrule\multicolumn{4}{l}{\textit{Panel B: Interaction of hydrocortisone and `xlabel'$^b$}} \\ \quad Interaction effect" " " "\midrule Participants" "Decisions per participant" "Decisions"))"'
	}
}
if `spec' == 1 local drop "drop(*)"
else local drop ""

local alignment = $eststo_counter * "$alignment"

esttab using "$tables_dir/spec`spec'_social_proximity_detailed.tex", $table_design ///
	`cons_label' `stats' `drop'  /// 
	mtitles("\specialcell{Social \\ Proximity}" "\specialcell{Likely to \\ be friends}" "\specialcell{Trust}" "\specialcell{Closeness}") ///
	alignment(`alignment') ///
	nonotes addnotes(`notesspec`spec'' `social_proximity_note' Likelihood to be friends and trust are set on Likert scales from 1 to 5 while closeness is set on a Likert scale from 0 to 5. `general_notes') ///
	substitute(\_ _ `notes_width`=$eststo_counter'')
noisily dis as result "Successfully created Social Proximity specification `spec' Table by ingredients."

********************************************************************************
******************************** Stacked analysis ******************************
********************************************************************************
include "$do_analysis_dir/stacked.do"

* Specification chart coefficient retrieval

foreach coeff in diff_eth pill eth_Delta {
	foreach game in cyd dg tg1 tg2 social_proximity {
		clear
		svmat2 `game'_`coeff', names(col) rnames(spec_name)
		save "$estimates_dir/`game'_`coeff'", replace
	}
}

noisily dis as input "End: Tables"
